/**
 * 检测图片是否存在
 * @param url
 */
let imageIsExist = function (url: string) {
  if (!url) return Promise.resolve();
  return new Promise((resolve) => {
    let img: any = new Image();
    img.onload = function () {
      if (this.complete == true) {
        resolve(img);
      }
    };
    img.onerror = function () {
      resolve(false);
      img = null;
    };
    img.src = url;
  });
};

export default defineNuxtPlugin((nuxtApp) => {
  
  nuxtApp.vueApp.directive("img-error", {
    created(a, b, c: any) {
      if (c && c.children && c.children.length > 0) {
        let idx = 0;
        let img = c.children.find((e: any, index: number) => {
          idx = index;
          return e.type === "img";
        });
        if (img) {
          let imgURL = img.props.src; //获取图片地址
          if (imgURL) {
            imageIsExist(imgURL).then((res: any) => {
              if (res) {
                img = res;
              } else {
                // console.log("img.onerror:", c.props.onOnerror);
                c.props.onOnerror && c.props.onOnerror();
              }
            });
          }
        }
      }
    },
    mounted() {
      // console.log("img-error--加载完成");
    },
    getSSRProps(binding, vnode) {
      // 你可以在这里提供SSR特定的props
      // console.log('getSSRProps--binding--',binding);
      // console.log('getSSRProps--vnode--',vnode);
      
      return {};
    },
    deep: true,
  });
});
